package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.log.constant.CrmLogMemoConstant;
import com.xbongbong.paas.pojo.dto.DynamicMigrationDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.DynamicDao;
import com.xbongbong.saas.domain.entity.DynamicEntity;
import com.xbongbong.saas.domain.entity.ext.CustomerCommunicateEntityExt;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.base.CommunicateBaseEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.model.CustomerCommunicateModel;
import com.xbongbong.saas.service.DynamicMigrationService;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.client.core.CountRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.rangeQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author: yingjf
 * @date: 2022/5/6 14:58
 * @description:
 */
@Service("dynamicMigrationServiceImpl")
public class DynamicMigrationServiceImpl implements DynamicMigrationService {
    private static final Logger LOG = LoggerFactory.getLogger(DynamicMigrationServiceImpl.class);
    @Resource
    private DynamicDao dynamicDao;
    @Resource
    private CustomerCommunicateModel customerCommunicateModel;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;


    /*@Override
    public void migration(DynamicMigrationDTO dynamicMigrationDTO) throws XbbException {
        List<String> corpidList = dynamicMigrationDTO.getCorpidList();
        List<String> excludeCorpidList = dynamicMigrationDTO.getExcludeCorpidList();
        Long gteId = dynamicMigrationDTO.getGteId();
        Long lteId = dynamicMigrationDTO.getLteId();
        Long count = dynamicMigrationDTO.getCount();
        //每次查询条数
        Integer pageNum = 1000;
        Map param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (count == null || count == 0L) {
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            if (CollectionsUtil.isNotEmpty(corpidList)) {
                boolQueryBuilder.filter(termsQuery("corpid.keyword", corpidList));
            }
            if (Objects.nonNull(gteId) && gteId != 0L) {
                boolQueryBuilder.filter(rangeQuery("id").gte(gteId));
            }
            if (Objects.nonNull(lteId) && lteId != 0L) {
                boolQueryBuilder.filter(rangeQuery("id").lte(lteId));
            }
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.indices(IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE.getIndex());
            searchRequest.source(sourceBuilder);
            CountRequest countRequest = new CountRequest(searchRequest.indices()[0]);
            countRequest.query(searchRequest.source().query());
            count = xbbElasticsearchRestTemplate.count(countRequest);
        }
        LOG.info("共需处理{}条", count);
        Long page = count / pageNum;
        if (page != 0) {
            page = count % page == 0 ? page : page + 1;
        }
        List<DynamicEntity> dynamicEntityList = null;
        DynamicEntity dynamicEntity = null;
        List<CustomerCommunicateEntityExt> communicateEntityExtList = null;
        JSONObject data = null;
        Long minId = null;
        Long maxId = null;
        int size = 0;
        String corpid = null;
        String dataId = null;
        Integer logType = null;
        String autoGen = null;
        String memo = null;
        String refId = null;
        Integer refBusinessType = null;
        String refName = null;
        String userName = null;
        String message = I18nMessageUtil.getMessage(CrmLogMemoConstant.DYNAMIC_USER_COMMUNICATE_ADD);
        for (int i = 0; i <= page; i++) {
            param.clear();
            if (CollectionsUtil.isNotEmpty(corpidList)) {
                param.put("corpidIn", corpidList);
            }
            if (Objects.nonNull(gteId) && gteId != 0L) {
                param.put("idGte", gteId);
            }
            if (Objects.nonNull(lteId) && lteId != 0L) {
                param.put("idLte", lteId);
            }
            param.put("start", i * pageNum);
            param.put("pageNum", pageNum);
            param.put("orderByStr", "id asc");
            param.put("del", DelEnum.NORMAL.getDel());
            communicateEntityExtList = customerCommunicateModel.findEntitysWithoutSub(param);
            if (CollectionsUtil.isEmpty(communicateEntityExtList)) {
                continue;
            }
            size = communicateEntityExtList.size();
            minId = communicateEntityExtList.get(0).getId();
            maxId = communicateEntityExtList.get(size - 1).getId();
            dynamicEntityList = new ArrayList<>();

            try {
                for (CustomerCommunicateEntityExt communicateEntityExt : communicateEntityExtList) {
                    corpid = communicateEntityExt.getCorpid();
                    if (CollectionsUtil.isNotEmpty(excludeCorpidList) && excludeCorpidList.contains(corpid)) {
                        // 跳过不处理的公司
                        continue;
                    }
                    dynamicEntity = new DynamicEntity();
                    data = communicateEntityExt.getData();
                    dynamicEntity.setCorpid(corpid);
                    dataId = data.getString(CustomerCommunicateEnum.CUSTOMER_NAME.getAttr());
                    if (dataId != null) {
                        dynamicEntity.setCustomerId(Long.parseLong(dataId));
                    } else {
                        // 脏数据  跟进记录的客户是必填的 select  count(1) from tb_saas_customer_communicate where log_type !=0 and  JSON_EXTRACT(data,"$.text_1") is null and corpid = corpid
                        continue;
                    }
                    logType = communicateEntityExt.getLogType();
                    dynamicEntity.setCreatorId(communicateEntityExt.getCreatorId());
                    dynamicEntity.setLogType(logType);
                    autoGen = data.getString(CommunicateBaseEnum.AUTO_GEN.getAttr());
                    memo = data.getString(CommunicateBaseEnum.MEMO.getAttr());
                    refId = data.getString(CustomerCommunicateEnum.COMMUNICATE_BUSINESS.getAttr());
                    if (StringUtil.isNotEmpty(refId)) {
                        dynamicEntity.setRefId(Long.parseLong(refId));
                    }
                    refBusinessType = FastJsonHelper.getIntegerFromFormData(data, CustomerCommunicateEnum.COMMUNICATE_BUSINESS_TYPE.getAttr());
                    if (Objects.nonNull(refBusinessType)) {
                        dynamicEntity.setRefBusinessType(refBusinessType);
                    }
                    refName = FastJsonHelper.getStringFromFormData(data, CustomerCommunicateEnum.COMMUNICATE_BUSINESS_LINK_TEXT.getAttr());
                    if ("0".equals(autoGen)) {
                        userName = data.getString(CommunicateBaseEnum.USER_NAME.getAttr()) == null ? "" : data.getString(CommunicateBaseEnum.USER_NAME.getAttr());
                        //%s 新建了一条跟进记录
                        memo = String.format(message, userName);
                        //特殊处理下跟进记录
                        refName = data.getString(CommunicateBaseEnum.MEMO.getAttr());
                        dynamicEntity.setRefId(communicateEntityExt.getDataId());
                        dynamicEntity.setRefBusinessType(XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode());
                    }
                    if (memo != null && memo.length() > 200) {
                        memo = memo.substring(0, 200);
                    }
                    dynamicEntity.setMemo(memo);
                    if (refName != null && refName.length() >= 100) {
                        refName = refName.substring(0, 100);
                    }
                    dynamicEntity.setRefName(refName);
                    dynamicEntity.setAddTime(communicateEntityExt.getAddTime());
                    dynamicEntity.setUpdateTime(communicateEntityExt.getUpdateTime());
                    dynamicEntity.setDel(0);
                    dynamicSetId(dynamicEntity);
                    dynamicEntityList.add(dynamicEntity);
                }
                if (CollectionsUtil.isNotEmpty(dynamicEntityList)) {
                    dynamicDao.insertList(dynamicEntityList);
                }
            } catch (Exception e) {
                LOG.error("id {} 至 {} 处理失败", minId, maxId, e);
            } finally {
                LOG.info("id {} 至 {} 处理完毕", minId, maxId);
            }
        }
    }*/

    @Override
    public void migration(DynamicMigrationDTO dynamicMigrationDTO) throws XbbException {
        List<String> corpidList = dynamicMigrationDTO.getCorpidList();
        List<String> excludeCorpidList = dynamicMigrationDTO.getExcludeCorpidList();
        Long gteId = dynamicMigrationDTO.getGteId();
        Long lteId = dynamicMigrationDTO.getLteId();

        if (lteId == null) {
            lteId = customerCommunicateModel.getMaxId();
        }

        if (gteId == null) {
            gteId = 0L;
        }

        //每次查询条数
        Integer pageNum = 10000;
        Map param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

        List<DynamicEntity> dynamicEntityList = null;
        DynamicEntity dynamicEntity = null;
        List<CustomerCommunicateEntityExt> communicateEntityExtList = null;
        JSONObject data = null;
        Long minId = null;
        Long maxId = null;
        int size = 0;
        String corpid = null;
        String dataId = null;
        Integer logType = null;
        String autoGen = null;
        String memo = null;
        String refId = null;
        Integer refBusinessType = null;
        String refName = null;
        String userName = null;
        String message = I18nMessageUtil.getMessage(CrmLogMemoConstant.DYNAMIC_USER_COMMUNICATE_ADD);
        boolean flag = true;
        while (flag) {
            if (CollectionsUtil.isNotEmpty(corpidList)) {
                param.put("corpidIn", corpidList);
            }
            if (Objects.nonNull(gteId)) {
                param.put("idGte", gteId);
            }
            if (Objects.nonNull(lteId) && lteId != 0L) {
                param.put("idLte", lteId);
            }
            param.put("start", 0);
            param.put("pageNum", pageNum);
            param.put("orderByStr", "id asc");
            param.put("del", DelEnum.NORMAL.getDel());
            communicateEntityExtList = customerCommunicateModel.findEntitysWithoutSub(param);
            if (CollectionsUtil.isEmpty(communicateEntityExtList)) {
                flag = false;
            } else {
                size = communicateEntityExtList.size();
                minId = communicateEntityExtList.get(0).getId();
                maxId = communicateEntityExtList.get(size - 1).getId();
                gteId = maxId;
            }
            if (size < pageNum) {
                flag = false;
            }

            dynamicEntityList = new ArrayList<>();
            try {
                for (CustomerCommunicateEntityExt communicateEntityExt : communicateEntityExtList) {
                    corpid = communicateEntityExt.getCorpid();
                    if (CollectionsUtil.isNotEmpty(excludeCorpidList) && excludeCorpidList.contains(corpid)) {
                        // 跳过不处理的公司
                        continue;
                    }
                    dynamicEntity = new DynamicEntity();
                    data = communicateEntityExt.getData();
                    dynamicEntity.setCorpid(corpid);
                    dataId = data.getString(CustomerCommunicateEnum.CUSTOMER_NAME.getAttr());
                    if (dataId != null) {
                        dynamicEntity.setCustomerId(Long.parseLong(dataId));
                    } else {
                        // 脏数据  跟进记录的客户是必填的 select  count(1) from tb_saas_customer_communicate where log_type !=0 and  JSON_EXTRACT(data,"$.text_1") is null and corpid = corpid
                        continue;
                    }
                    logType = communicateEntityExt.getLogType();
                    dynamicEntity.setCreatorId(communicateEntityExt.getCreatorId());
                    dynamicEntity.setLogType(logType);
                    autoGen = data.getString(CommunicateBaseEnum.AUTO_GEN.getAttr());
                    memo = data.getString(CommunicateBaseEnum.MEMO.getAttr());
                    refId = data.getString(CustomerCommunicateEnum.COMMUNICATE_BUSINESS.getAttr());
                    if (StringUtil.isNotEmpty(refId)) {
                        dynamicEntity.setRefId(Long.parseLong(refId));
                    }
                    refBusinessType = FastJsonHelper.getIntegerFromFormData(data, CustomerCommunicateEnum.COMMUNICATE_BUSINESS_TYPE.getAttr());
                    if (Objects.nonNull(refBusinessType)) {
                        dynamicEntity.setRefBusinessType(refBusinessType);
                    }
                    refName = FastJsonHelper.getStringFromFormData(data, CustomerCommunicateEnum.COMMUNICATE_BUSINESS_LINK_TEXT.getAttr());
                    if ("0".equals(autoGen)) {
                        userName = data.getString(CommunicateBaseEnum.USER_NAME.getAttr()) == null ? "" : data.getString(CommunicateBaseEnum.USER_NAME.getAttr());
                        //%s 新建了一条跟进记录
                        memo = String.format(message, userName);
                        //特殊处理下跟进记录
                        refName = data.getString(CommunicateBaseEnum.MEMO.getAttr());
                        dynamicEntity.setRefId(communicateEntityExt.getDataId());
                        dynamicEntity.setRefBusinessType(XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode());
                    }
                    if (memo != null && memo.length() > 200) {
                        memo = memo.substring(0, 200);
                    }
                    dynamicEntity.setMemo(memo);
                    if (refName != null && refName.length() >= 100) {
                        refName = refName.substring(0, 100);
                    }
                    dynamicEntity.setRefName(refName);
                    dynamicEntity.setAddTime(communicateEntityExt.getAddTime());
                    dynamicEntity.setUpdateTime(communicateEntityExt.getUpdateTime());
                    dynamicEntity.setDel(0);
                    dynamicSetId(dynamicEntity);
                    dynamicEntityList.add(dynamicEntity);
                }
                if (CollectionsUtil.isNotEmpty(dynamicEntityList)) {
                    dynamicDao.insertList(dynamicEntityList);
                }
            } catch (Exception e) {
                LOG.error("id {} 至 {} 处理失败", minId, maxId, e);
            } finally {
                LOG.info("id {} 至 {} 处理完毕", minId, maxId);
            }
        }


    }

    /**
     * 设置
     * date: 2022/6/22 9:30 上午
     *
     * @param dynamicEntity:
     * @author yingjf
     */
    private void dynamicSetId(DynamicEntity dynamicEntity) {
        Long parentDataId = dynamicEntity.getRefId();
        Integer parentBusinessType = dynamicEntity.getRefBusinessType();
        if (parentDataId == null || parentBusinessType == null) {
            return;
        }

        /*if(Objects.equals(parentBusinessType,XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())){
            dynamicEntity.setCustomerId(parentDataId);
        }*/
        if (Objects.equals(parentBusinessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode())) {
            dynamicEntity.setOpportunityId(parentDataId);
        } else if (Objects.equals(parentBusinessType, XbbRefTypeEnum.CONTACT.getCode())) {
            dynamicEntity.setContactId(parentDataId);
        } else if (Objects.equals(parentBusinessType, XbbRefTypeEnum.CONTRACT.getCode())) {
            dynamicEntity.setContractId(parentDataId);
        }
    }
}
